<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use OSS\OssClient;
use OSS\Core\OssException;
use think\Request;

/**
 * 阿里云OSS管理
 *
 * @icon fa fa-circle-o
 */
class Oss extends Backend
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function uploadFile()
    {
        $file = request()->file('file');
        if (empty($file)) {
            $this->error('请选择文件');
        } else {
            //本地文件
            $fileInfo = $file->getInfo();
            //上传成功
            vendor('autoload');
            $accessKeyId = "LTAI4G9bayZoFBJBUv7aWCBG";//去阿里云后台获取秘钥
            $accessKeySecret = "yyjpqccrbSX1rE3Kvz7sFqcEyLAXAh";//去阿里云后台获取秘钥
            $endpoint = "oss-cn-hangzhou.aliyuncs.com";//你的阿里云OSS地址
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $bucket = "hongjide";//oss中的文件上传空间
            $object = date('Y-m-d') . '/' . $fileInfo['name'];//想要保存文件的名称
            try {
                $res = $ossClient->uploadFile($bucket, $object, $fileInfo['tmp_name']);
                $this->success(__('Uploaded successful'), '', ['url' => $res['info']['url'], 'fullurl' => cdnurl($res['info']['url'], true)]);
                //上传成功，自己编码
                //这里可以删除上传到本地的文件。unlink（$file）；
            } catch (OssException $e) {
                //上传失败，自己编码
                printf($e->getMessage() . "\n");
                return;
            }
        }
    }
}